const koa = require('koa')
const app = new koa()
const mongoose = require('mongoose')
const db = require('./db/config')

// 导入路由
const Interface  =  require('./router/index')
const routerKeys = Object.keys(Interface)

// 导入配置文件
const config = require('./config/index')

// 挂载工具库
const utils = require('./utils/index')
const utilsKeys = Object.keys(utils)
utilsKeys.forEach(item => {
  global[item] = utils[item]
});

(async() => {
  // 注册路由
  await routerKeys.forEach(item => {
    app.use(Interface[item].routes()).use(Interface[item].allowedMethods())
  })
  await mongoose.connect(db.dbUrl, {
    useNewUrlParser: true
  }, err => {
    if (err) return LOG.error('数据库连接失败：' + err)
    LOG.success('数据库连接成功')
  })
  await app.listen(config.service.port, config.service.host, err => {
    if (err) return LOG.error('server端工程启动失败：' + err)
    LOG.success(`server端工程启动成功： http://${config.service.host}:${config.service.port}`)
  })
})()